﻿using AutoMapper;
using B.ERP.Domain;
using B.ERP.Services.Input;
using B.ERP.Services.OutPut;
using Infrastructure;
using IoTClient;
using Microsoft.AspNetCore.Mvc;
using Standard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace B.ERP.Services
{
    public class BOMServices : IBOMServices
    {
        private readonly MesRepository<BomModel> _bomRepository;
        private readonly MesRepository<BomMaterialIdModel> _materialRepository;
        private readonly MesRepository<Parent_ChildrenModel> _parentchildRepository;
        private readonly IMapper mapper;

        public BOMServices(IMapper mapper, MesRepository<BomMaterialIdModel> materialRepository, MesRepository<BomModel> bomRepository, MesRepository<Parent_ChildrenModel> parentchildRepository)
        {

            this.mapper = mapper;
            _materialRepository = materialRepository;
            _bomRepository = bomRepository;
            _parentchildRepository = parentchildRepository;
        }

        public ApiResult<int> AddBom(AddBomInput Input)
        {
           var result=new ApiResult<int>();
           var data=mapper.Map<BomModel>(Input);
            data.Id=YitIdHelper.NextId().ToString();
            data.CreatedBy = "admin";
            data.UpdatedAt = DateTime.Now;

            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _bomRepository.Add(data),
                Message = "添加成功"
            };
        }

        public ApiResult<int> AddMaterial(AddMaterialInput addMaterialInput)
        {
            var result = new ApiResult<int>();
            var model = mapper.Map<BomMaterialIdModel>(addMaterialInput);
            model.Id = YitIdHelper.NextId().ToString();
            model.IsDeleted = false;
            model.CreatedAt = DateTime.Now;
            model.CreatedBy = "admin";
            //中间表
            Parent_ChildrenModel bommaterial=new Parent_ChildrenModel();
            bommaterial.Id = YitIdHelper.NextId().ToString();
            bommaterial.MaterialId = model.Id;
            bommaterial.BomId = addMaterialInput.BomId;
            _parentchildRepository.Add(bommaterial);
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _materialRepository.Add(model),
                Message = "添加成功"
            };
        }

        public ApiResult<List<GetBomDTO>> GetBom()
        {
            var result=new ApiResult<List<GetBomDTO>>();
            var list = _bomRepository.GetList();
            result.ResultData=mapper.Map<List<GetBomDTO>>(list);
            result.Code=ApiCode.Success;
            result.Message="查询成功";
            return result;

        }

        public ApiPaging<GetMaterialOutPut> GetMaterial(SearchMaterialInput searchMaterialInput)
        {
            var result = new ApiPaging<List<GetMaterialOutPut>>();
            var model = _materialRepository.GetQueryable(x => x.IsDeleted == false);
            if (!string.IsNullOrEmpty(searchMaterialInput.MaterialName))
            {
                model = model.Where(x => x.MaterialName.Contains(searchMaterialInput.MaterialName));
            }
            return new ApiPaging<GetMaterialOutPut>
            {
                TotalCount = model.Count(),
                TotalPage = (int)Math.Ceiling(model.Count() * 1.0 / searchMaterialInput.PageSize),
                PageDatas = mapper.Map<List<GetMaterialOutPut>>(model.OrderByDescending(x => x.CreatedAt).Skip((searchMaterialInput.PageIndex - 1) * searchMaterialInput.PageSize).Take(searchMaterialInput.PageSize).ToList())
            };
        }

        public ApiResult<List<GetMaterialOutPut>> GetMaterialcount()
        {

            var result = new ApiResult<List<GetMaterialOutPut>>();
            var data = _materialRepository.GetList();
            var list = mapper.Map<List<GetMaterialOutPut>>(data);
            return new ApiResult<List<GetMaterialOutPut>>
            {
                Code = ApiCode.Success,
                ResultData = list
            };
        }

        public ApiResult<int> MaterialDeleteList(List<string> Ids)
        {
            var result = new ApiResult<int>();
            var model = _materialRepository.GetList();
            foreach (var item in Ids)
            {
                var id = model.FirstOrDefault(x => x.Id == item)!;
                id.IsDeleted = true;
                _materialRepository.Update(id);
            }
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = 1,
                Message = "删除成功"
            };
        }

        public ApiResult<int> UpdateMaterial(EditMaterialInput editMaterialInput)
        {
            var result = new ApiResult<int>();
            var model = _materialRepository.GetQueryable(X => X.Id == editMaterialInput.Id).First();
            var data = mapper.Map<BomMaterialIdModel>(editMaterialInput);
            data.CreatedAt = model.CreatedAt;
            data.CreatedBy = model.CreatedBy;
            data.UpdatedAt = DateTime.Now;
            data.UpdatedBy = "admin";
            int r = _materialRepository.Update(data);
            if (r > 0)
            {
                result.Code = ApiCode.Success;
                result.Message = "修改成功";
                return result;
            }
            else
            {
                result.Code = ApiCode.InternalError;
                result.Message = "修改失败";
                return result;
            }
        }
        /// <summary>
        /// 树形Bom
        /// </summary>
        /// <returns></returns>
        public ApiResult<List<TreeDTO>> TreeBom()
        {
            try
            {
                // 只查最近30天的BOM
                var allBoms = _bomRepository.GetQueryable(x=>x.IsDeleted==false).ToList();
                var bomIds = allBoms.Select(b => b.Id).ToList();

                // 只查相关父子关系
                var relations = _parentchildRepository.GetQueryable(r => bomIds.Contains(r.BomId)).ToList();
                var materialIds = relations.Select(r => r.MaterialId).Distinct().ToList();
                // 只查相关物料
                var allMaterials = _materialRepository.GetQueryable(m => materialIds.Contains(m.Id)).ToList();

                // 构建父ID -> 子ID 列表映射（BOM ID -> Material ID）
                var parentToMaterials = relations
                    .GroupBy(r => r.BomId)
                    .ToDictionary(g => g.Key, g => g.Select(r => r.MaterialId).ToList());

                var result = new List<TreeDTO>();

                foreach (var bom in allBoms)
                {
                    var dto = new TreeDTO
                    {
                        Bom = bom,
                        Children = new List<BomMaterialIdModel>()
                    };

                    if (parentToMaterials.TryGetValue(bom.Id, out var mIds))
                    {
                        // 查找该 BOM 对应的所有子级物料
                        dto.Children = allMaterials
                            .Where(m => mIds.Contains(m.Id))
                            .ToList();
                    }

                    result.Add(dto);
                }

                return new ApiResult<List<TreeDTO>>
                {
                    Code = ApiCode.Success,
                    ResultData = result,
                    Message = "查询成功(仅近30天数据)"
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return new ApiResult<List<TreeDTO>>
                {
                    ResultData = null,
                    Message = ex.Message
                };
            }
           
        }

    }
}
